/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.utils.id.IdWorker;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.user.dto.FinanceRecordPageDTO;
import com.pig4cloud.pigx.user.entity.FinanceFuel;
import com.pig4cloud.pigx.user.entity.FinanceRecord;
import com.pig4cloud.pigx.user.entity.TransferDetailed;
import com.pig4cloud.pigx.user.enums.FinanceRecordEnums;
import com.pig4cloud.pigx.user.service.FinanceRecordService;
import com.pig4cloud.pigx.user.vo.AdminPageDemoVO;
import com.pig4cloud.pigx.user.vo.SaveFinanceDTO;
import com.pig4cloud.pigx.user.vo.UnassignedFinanceVO;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 财务记录
 *
 * @author pigx code generator
 * @date 2023-02-02 16:58:30
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/finance_record" )
@Api(value = "finance_record", tags = "财务记录管理")
public class FinanceRecordController {

    private final FinanceRecordService financeRecordService;

	private final IdWorker idWorker;


	@GetMapping
	@PreAuthorize("@pms.hasPermission('user_financerecord_view')" )
	public R<List<TransferDetailed>> getUnassigned(@RequestParam("transferType") String transferType, @RequestParam("financeType") String financeType) {
		return financeRecordService.getUnassigned(transferType, financeType);
	}

	/**
	 * 获取总人工充值
	 * @return r
	 */
	@GetMapping("/user/recharge")
	public R<BigDecimal> getUserRechargeSum() {
		return financeRecordService.getUserRechargeSum();
	}

	/**
	 * 获取用户资金/奖励账户总结余
	 * @return r
	 */
	@GetMapping("/user/capital")
	public R<BigDecimal> getUserCapitalBalanceSum(@RequestParam("type") String type) {
		return financeRecordService.getUserCapitalBalanceSum(type);
	}

    /**
     * 分页查询
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('user_financerecord_view')" )
    public R<AdminPageDemoVO<FinanceRecord>> getFinanceRecordPage(FinanceRecordPageDTO dto) {
		QueryWrapper<FinanceRecord> wrapper = new QueryWrapper<FinanceRecord>() {{
			if (dto.getStartTime() != null) {
				ge("create_time", dto.getStartTime());
			}
			if (dto.getEndTime() != null) {
				le("create_time", dto.getEndTime());
			}
			if (dto.getType() != null && !dto.getType().isEmpty()) {
				eq("type", dto.getType());
			}
			if (dto.getChain() != null && !dto.getChain().isEmpty()) {
				eq("chain", dto.getChain());
			}
			orderByDesc("create_time");
		}};
		Page<FinanceRecord> page = financeRecordService.page(new Page<FinanceRecord>() {{
			setCurrent(dto.getCurrent());
			setSize(dto.getSize());
		}},wrapper);
		for (FinanceRecord record : page.getRecords()) {
			record.setType(FinanceRecordEnums.Type.findName(record.getType()));
			record.setStatus(FinanceRecordEnums.Status.findName(record.getStatus()));
		}
		FinanceRecord one = financeRecordService.getOne(wrapper.select("sum(quantity) 'quantity'"));
		return R.ok(new AdminPageDemoVO<FinanceRecord>(){{
			setPage(page);
			setStatistics(one);
		}});
    }

	/**
	 * 根据分配记录获取分配的燃料购买记录id
	 * @param id 分配id
	 * @return r
	 */
	@GetMapping("/fuel/{id}" )
	public R<List<Long>> getBuyFuelList(@PathVariable("id" ) Long id) {
		List<FinanceFuel> financeFuels = new FinanceFuel().selectList(new QueryWrapper<FinanceFuel>() {{
			eq("finance_record_id", id);
		}});
		return R.ok(financeFuels.stream().map(FinanceFuel::getBuyFuelId).collect(Collectors.toList()));
	}


    /**
     * 通过id查询财务记录
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('user_financerecord_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(financeRecordService.getById(id));
    }

    /**
     * 新增财务记录
     * @return R
     */
    @ApiOperation(value = "新增财务记录", notes = "新增财务记录")
    @SysLog("新增财务记录" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('user_financerecord_add')" )
    public R save(@RequestBody SaveFinanceDTO dto) {
        return R.ok(financeRecordService.save(dto));
    }

    /**
     * 修改财务记录
     * @param financeRecord 财务记录
     * @return R
     */
    @ApiOperation(value = "修改财务记录", notes = "修改财务记录")
    @SysLog("修改财务记录" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('user_financerecord_edit')" )
    public R updateById(@RequestBody FinanceRecord financeRecord) {
        return R.ok(financeRecordService.updateById(financeRecord));
    }

    /**
     * 通过id删除财务记录
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除财务记录", notes = "通过id删除财务记录")
    @SysLog("通过id删除财务记录" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('user_financerecord_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(financeRecordService.removeById(id));
    }


    /**
     * 导出excel 表格
     * @param financeRecord 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('user_financerecord_export')" )
    public List<FinanceRecord> export(FinanceRecord financeRecord) {
        return financeRecordService.list(Wrappers.query(financeRecord));
    }
}
